<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\ProductCart;
use app\common\model\ProductSpec;
use app\common\tool\Result;
use think\Response;

class Cart extends Base
{
    public function index(): Response
    {
        $list = ProductCart::field('id,pid,spec,num')->where(['uid' => $this->user->id])
            ->order('update_time desc,id desc')->select();
        foreach ($list as $info) {
            $info->title = $info->product->title;
            $info->icon = $info->product->icon;
            $info->vip_price = $info->product->vip_price;
            if ($info->spec) {
                $specInfo = ProductSpec::where(['pid' => $info->pid, 'merge_title' => $info->spec])->find();
                $info->icon = $specInfo->icon ?: $info->product->icon;
                $info->vip_price = $specInfo->vip_price;
            }
            unset($info->product);
        }

        return Result::success('success', $list);
    }

    public function add(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(ProductCart::add($param, $this->user));
    }

    public function edit(): Response
    {
        $param = $this->request->post();
        if ($param['type'] == 3) {
            $param['cart_id'] = $param['id'] ? explode(',', $param['id']) : '';
        }

        return Result::fastReturn(ProductCart::edit($param, $this->user));
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $param['type'] = 2;
        $param['cart_id'] = $param['cart_id'] ? explode(',', $param['cart_id']) : '';
        $res = OrderTemporary::setTemporary($param, $this->user);
        if ($res['code'] === -1) {
            return Result::fail($res['msg']);
        }

        return Result::success($res['msg']);
    }
}